"use client"

import * as React from "react"
import type {
  ColumnFiltersState,
  SortingState,
  VisibilityState,
} from "@tanstack/react-table"
import {
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import { ChevronDown, Settings2 } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { createColumns } from "./columns"
import type { Contact } from "./columns"

interface ContactsDataTableProps {
  data: Contact[]
  loading?: boolean
  onEdit: (contact: Contact) => void
  onDelete: (contact: Contact) => void
  onToggleFavorite: (contact: Contact) => void
  onBatchDelete: (contacts: Contact[]) => void
  onBatchToggleFavorite: (contacts: Contact[], isFavorite: boolean) => void
  onExport: (contacts: Contact[]) => void
  groups: string[]
  tags: string[]
  onGroupFilter: (group: string | null) => void
  onTagFilter: (tag: string | null) => void
  onFavoriteFilter: (isFavorite: boolean | null) => void
  currentGroupFilter: string | null
  currentTagFilter: string | null
  currentFavoriteFilter: boolean | null
}

export function ContactsDataTable({
  data,
  loading = false,
  onEdit,
  onDelete,
  onToggleFavorite,
  onBatchDelete,
  onBatchToggleFavorite,
  onExport,
  groups,
  tags,
  onGroupFilter,
  onTagFilter,
  onFavoriteFilter,
  currentGroupFilter,
  currentTagFilter,
  currentFavoriteFilter
}: ContactsDataTableProps) {
  const [sorting, setSorting] = React.useState<SortingState>([])
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
  const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
  const [rowSelection, setRowSelection] = React.useState({})
  const [globalFilter, setGlobalFilter] = React.useState("")

  const columns = React.useMemo(
    () => createColumns({ onEdit, onDelete, onToggleFavorite }),
    [onEdit, onDelete, onToggleFavorite]
  )

  const table = useReactTable({
    data,
    columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    onGlobalFilterChange: setGlobalFilter,
    globalFilterFn: (row, columnId, filterValue) => {
      const contact = row.original
      const searchValue = filterValue.toLowerCase()
      
      return !!(
        contact.name.toLowerCase().includes(searchValue) ||
        (contact.phone && contact.phone.includes(searchValue)) ||
        (contact.email && contact.email.toLowerCase().includes(searchValue)) ||
        (contact.company && contact.company.toLowerCase().includes(searchValue)) ||
        (contact.position && contact.position.toLowerCase().includes(searchValue))
      )
    },
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
      globalFilter,
    },
  })

  // 获取选中的联系人
  const selectedContacts = React.useMemo(() => {
    return table.getFilteredSelectedRowModel().rows.map(row => row.original)
  }, [table.getFilteredSelectedRowModel().rows])

  // 清除选择
  const clearSelection = () => {
    setRowSelection({})
  }

  // 处理批量操作
  const handleBatchDelete = (contacts: Contact[]) => {
    if (confirm(`确定要删除选中的 ${contacts.length} 个联系人吗？`)) {
      onBatchDelete(contacts)
      clearSelection()
    }
  }

  const handleBatchToggleFavorite = (contacts: Contact[], isFavorite: boolean) => {
    onBatchToggleFavorite(contacts, isFavorite)
    clearSelection()
  }

  const handleExport = (contacts: Contact[]) => {
    onExport(contacts)
  }

  return (
    <div className="w-full">
      {/* 工具栏 */}
      <div className="flex items-center py-4 gap-4">
        {/* 全局搜索 */}
        <Input
          placeholder="搜索联系人（姓名、电话、邮箱、公司）..."
          value={globalFilter}
          onChange={(event) => setGlobalFilter(event.target.value)}
          className="max-w-sm"
        />

        {/* 分组筛选 */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="ml-auto">
              分组 {currentGroupFilter ? `(${currentGroupFilter})` : ""}
              <ChevronDown className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuCheckboxItem
              checked={!currentGroupFilter}
              onCheckedChange={() => onGroupFilter(null)}
            >
              全部分组
            </DropdownMenuCheckboxItem>
            {groups.map((group) => (
              <DropdownMenuCheckboxItem
                key={group}
                checked={currentGroupFilter === group}
                onCheckedChange={() => onGroupFilter(group)}
              >
                {group}
              </DropdownMenuCheckboxItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* 标签筛选 */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline">
              标签 {currentTagFilter ? `(${currentTagFilter})` : ""}
              <ChevronDown className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuCheckboxItem
              checked={!currentTagFilter}
              onCheckedChange={() => onTagFilter(null)}
            >
              全部标签
            </DropdownMenuCheckboxItem>
            {tags.map((tag) => (
              <DropdownMenuCheckboxItem
                key={tag}
                checked={currentTagFilter === tag}
                onCheckedChange={() => onTagFilter(tag)}
              >
                {tag}
              </DropdownMenuCheckboxItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* 收藏筛选 */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline">
              收藏 {currentFavoriteFilter !== null ? `(${currentFavoriteFilter ? '已收藏' : '未收藏'})` : ""}
              <ChevronDown className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuCheckboxItem
              checked={currentFavoriteFilter === null}
              onCheckedChange={() => onFavoriteFilter(null)}
            >
              全部
            </DropdownMenuCheckboxItem>
            <DropdownMenuCheckboxItem
              checked={currentFavoriteFilter === true}
              onCheckedChange={() => onFavoriteFilter(true)}
            >
              已收藏
            </DropdownMenuCheckboxItem>
            <DropdownMenuCheckboxItem
              checked={currentFavoriteFilter === false}
              onCheckedChange={() => onFavoriteFilter(false)}
            >
              未收藏
            </DropdownMenuCheckboxItem>
          </DropdownMenuContent>
        </DropdownMenu>

        {/* 列可见性 */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" className="ml-auto">
              <Settings2 className="mr-2 h-4 w-4" />
              列
              <ChevronDown className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {table
              .getAllColumns()
              .filter((column) => column.getCanHide())
              .map((column) => {
                return (
                  <DropdownMenuCheckboxItem
                    key={column.id}
                    className="capitalize"
                    checked={column.getIsVisible()}
                    onCheckedChange={(value) =>
                      column.toggleVisibility(!!value)
                    }
                  >
                    {column.id === 'select' ? '选择' :
                     column.id === 'name' ? '姓名' :
                     column.id === 'phone' ? '电话' :
                     column.id === 'email' ? '邮箱' :
                     column.id === 'company' ? '公司' :
                     column.id === 'group' ? '分组' :
                     column.id === 'tags' ? '标签' :
                     column.id === 'is_favorite' ? '收藏' :
                     column.id === 'address' ? '地址' :
                     column.id === 'created_at' ? '创建时间' :
                     column.id === 'actions' ? '操作' : column.id}
                  </DropdownMenuCheckboxItem>
                )
              })}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* 表格 */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => {
                  return (
                    <TableHead key={header.id}>
                      {header.isPlaceholder
                        ? null
                        : flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                    </TableHead>
                  )
                })}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={columns.length} className="h-24 text-center">
                  加载中...
                </TableCell>
              </TableRow>
            ) : table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={columns.length} className="h-24 text-center">
                  暂无数据
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页 */}
      <div className="flex items-center justify-end space-x-2 py-4">
        <div className="flex-1 text-sm text-muted-foreground">
          {table.getFilteredSelectedRowModel().rows.length} of{" "}
          {table.getFilteredRowModel().rows.length} 行已选中
        </div>
        <div className="space-x-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
          >
            上一页
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
          >
            下一页
          </Button>
        </div>
      </div>

      {/* 批量操作栏 */}
      {selectedContacts.length > 0 && (
        <div className="fixed bottom-4 left-1/2 transform -translate-x-1/2 z-50">
          <div className="bg-background border rounded-lg shadow-lg p-4 flex items-center gap-3">
            <div className="text-sm text-muted-foreground">
              已选择 {selectedContacts.length} 个联系人
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => handleBatchToggleFavorite(selectedContacts, true)}
                className="h-8"
              >
                添加到收藏
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handleBatchToggleFavorite(selectedContacts, false)}
                className="h-8"
              >
                取消收藏
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handleExport(selectedContacts)}
                className="h-8"
              >
                导出选中
              </Button>
              <Button
                variant="destructive"
                size="sm"
                onClick={() => handleBatchDelete(selectedContacts)}
                className="h-8"
              >
                删除选中
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={clearSelection}
                className="h-8 w-8 p-0"
              >
                ×
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
